import { defineStore } from 'pinia'
import { computed, ref, watch } from 'vue'
import { useDeviceMaintenanceProjectStore } from './project'
import { Part } from '@/types/system/device-maintenance/part'
import { PollingTask } from '@/types/system/device-maintenance/polling-task'
import * as api from '@/api/axios/device-maintenance-client'
import { getConfigsAsync } from '@/api/axios/device-server-client'
import { ShowDeleteMessageBoxAsync } from '@/utils/message-box'

export const useDeviceMaintenancePollingTaskStore = defineStore(
  'device-maintenance-polling-task',
  () => {
    // 项目名列表
    const projectNames = computed(() => {
      return useDeviceMaintenanceProjectStore().projectNames
    })

    // 部件名列表
    const partNames = computed(() => {
      return parts.value.map((item) => item.partName)
    })

    const isLoading = ref(false)

    // 是否已经首次加载
    const isLoad = ref(false)

    // 当前项目
    const currentProjectName = ref('')
    // 当前部件
    const currentPartName = ref('')
    // 部件列表
    const parts = ref<Part[]>([])
    // 轮询任务列表
    const tasks = ref<PollingTask[]>([])
    // 设备名列表
    const deviceNames = ref<string[]>([])
    // 是否已经选择有效的部件
    const isValidPart = computed(() => {
      return currentPartName.value != '' && currentPartName.value != null
    })

    // 项目变更，重置部件列表
    watch(currentProjectName, async (newValue) => {
      if (newValue != null && newValue != '') {
        openLoading()
        await loadPartsAsync()
        closeLoading()
        currentPartName.value = ''
        tasks.value = []
      }
    })

    // 部件变更，重置任务列表
    watch(currentPartName, async (newValue) => {
      if (newValue != null && newValue != '') {
        openLoading()
        await updatePollingTaskAsync()
        closeLoading()
      } else {
        tasks.value = []
      }
    })

    async function loadAsync() {
      openLoading()
      await loadProjectsAsync()
      await loadPartsAsync()
      closeLoading()
      isLoad.value = true
    }

    // 加载项目
    async function loadProjectsAsync() {
      const store = useDeviceMaintenanceProjectStore()
      // 判断是否需要加载项目信息
      if (store.isNeedLoadProjects) {
        const result = await store.updateProjectsAsync()
        if (!result) {
          return false
        }
      }
    }

    // 加载部件列表
    async function loadPartsAsync() {
      const store = useDeviceMaintenanceProjectStore()
      const currentProject = store.projects.find(
        (item) => item.projectName == currentProjectName.value
      )
      if (currentProject != null) {
        const result = await api.getPartsAsync(currentProject.id)
        if (result.isSuccess) {
          parts.value = result.result ?? []
          return true
        }
      }
    }

    // 更新轮询任务列表
    async function updatePollingTaskAsync() {
      const currentPart = parts.value.find((item) => item.partName == currentPartName.value)
      if (currentPart != null) {
        const result = await api.getPollingTasksAsync(currentPart.id)
        if (result.isSuccess) {
          tasks.value = result.result ?? []
        }
        const configsResult = await getConfigsAsync(currentPart.deviceId)
        if (configsResult.isSuccess) {
          deviceNames.value = configsResult.result?.map((item) => item.deviceName) ?? []
        }
        return result.isSuccess && configsResult.isSuccess
      }
      return false
    }

    // 插入一个轮询任务
    async function insertPollingTaskAsync(task: PollingTask) {
      const currentPart = parts.value.find((item) => item.partName == currentPartName.value)
      if (currentPart == null) {
        return false
      }
      task.partId = currentPart.id
      openLoading()
      const result = await api.insertPollingTaskAsync(task)
      await updatePollingTaskAsync()
      closeLoading()
      return result.isSuccess
    }

    async function deletePollingTaskAsync(index: number) {
      if (!(await ShowDeleteMessageBoxAsync())) {
        return
      }

      openLoading()
      const result = await api.deletePollingTaskAsync(tasks.value[index].id)
      if (result.isSuccess) {
        await updatePollingTaskAsync()
      }
      closeLoading()
      return result.isSuccess
    }

    function openLoading() {
      isLoading.value = true
    }

    function closeLoading() {
      isLoading.value = false
    }

    return {
      isLoading,
      isLoad,
      currentProjectName,
      currentPartName,
      isValidPart,
      projectNames,
      partNames,
      deviceNames,
      tasks,
      loadAsync,
      insertPollingTaskAsync,
      deletePollingTaskAsync
    }
  }
)
